package com.geek.novel.activity.book

import android.graphics.Color
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.adapter.BaseRecyclerViewAdapter
import com.geek.novel.adapter.BookDownloadListAdapter
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.dialog.MenuListDialog
import com.geek.novel.entity.BookDownload
import com.geek.novel.event.EventObserver
import com.geek.novel.listener.MenuItemInflaterViewListener
import com.geek.novel.services.BookDownloadRepository
import com.geek.novel.services.manager.BookDownloadManager
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.ToastUtils
import kotlinx.android.synthetic.main.activity_book_download.*


/**书籍缓存页面*/
class BookDownloadActivity: TitleBarActivity(), EventObserver {

	/**书籍列表*/
	private var listData: ArrayList<BookDownload> = ArrayList()

	/**每页显示条数*/
	private var pageSize: Int = 10

	/**准备下载的书籍id*/
	private var bookId: String? = null

	/**书籍列表的适配器*/
	private lateinit var listAdapter: BookDownloadListAdapter

	/**书籍缓存的数据库服务类*/
	private val bookDownloadRepository = BookDownloadRepository.getInstance()

	/**书籍全本缓存的管理器*/
	private val bookDownloadManager = BookDownloadManager.getInstance()

	/**当前长按选中的书籍的下标*/
	private var curBookSelectPosition = -1
	/**菜单的弹出框*/
	private lateinit var menuListDialog: MenuListDialog

	override fun pageName(): String = AppContext.getContext().getString(R.string.title_bar_book_download)

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_book_download)

		try {//设置背景为白色
			super.setBackgroundColor(Color.WHITE)

			//初始化信息
			this.initActivity()

			//注册事件监听器
			bookDownloadManager.addEventObserver(this)

			//初始化跳转到搜索页面的图标按钮
			this.initSearchIconBtn()

			//初始化下拉刷新功能
			this.initRefreshLayout()

			//初始化列表
			this.initListView()

			//初始化长按菜单的弹框
			this.initMenuListDialog()

			//获取缓存任务数据
			this.queryData()

		} catch (e: Exception) {
			ToastUtils.toast(e.message)
			finish()
		}

	}

	/**页面销毁*/
	override fun onDestroy() {
		super.onDestroy()

		//移除事件监听器
		bookDownloadManager.removeEventObserver(this)
	}

	/**初始化信息*/
	private fun initActivity(){
		val bundle = intent.extras?:Bundle()
		this.bookId = bundle.getString("bookId")
	}

	/**初始化显示跳转到搜索页面的图标按钮*/
	private fun initSearchIconBtn(){
//		super.showIconBtn(R.drawable.icon_menu_search)
	}

	/**图标按钮点击事件*/
	override fun onIconBtnClick(view: View) {
	}

	/**获取缓存任务数据*/
	private fun queryData() {
		//发起请求
		this.resetSearchBook()
		//搜索
		this.searchData()
	}

	/**附加控件*/
	override fun attachViewChild() {
	}

	/**绑定事件*/
	override fun bindEventChild() {
	}

	/**重置搜索下标*/
	private fun resetSearchBook(){
		book_download_refresh_layout.resetNoMoreData()
		this.listData.clear()
	}

	/**搜索*/
	private fun searchData(){
		var lastId = 0L
		if(listData.isNotEmpty()){
			lastId = listData[listData.size-1].id
		}
		val pager = bookDownloadRepository.findDownloadingBookPage(lastId, pageSize)

		try {
			val records = pager.records ?: throw Exception("获取查询结果异常！")
			listData.addAll(records)
			listAdapter.notifyDataSetChanged()

			this.checkListEmpty()

			book_download_refresh_layout.finishRefresh(true)
			//处理滚动加载
			val noMoreData = pager.total <= listData.size
			book_download_refresh_layout.finishLoadMore(0, true, noMoreData)
		} catch (e: Exception) {
			ToastUtils.toast(e.message)
			LogCatUtil.e("???", e.message, e)

			book_download_refresh_layout.finishRefresh(false)
			book_download_refresh_layout.finishLoadMore(false)
		}

	}

	/**检查书籍列表是否为空*/
	private fun checkListEmpty(): Boolean{
		val view = ly_book_download_no_result
		//书架列表为空的情况，添加书籍按钮
		if(listData.isEmpty()){
			view.visibility = View.VISIBLE
		}else{
			view.visibility = View.GONE
		}
		return listData.isEmpty()
	}

	/**
	 * 初始化下拉刷新功能
	 */
	private fun initRefreshLayout(){
		book_download_refresh_layout.setRefreshHeader(book_download_classics_header)
		book_download_refresh_layout.setRefreshFooter(book_download_classics_footer)
		//下拉刷新
		book_download_refresh_layout.setOnRefreshListener {
			this.resetSearchBook()
			this.searchData()
		}
		//滚动加载
		book_download_refresh_layout.setOnLoadMoreListener{
			this.searchData()
		}
	}

	/**初始化长按菜单的弹框*/
	private fun initMenuListDialog(){
		val menuList = ArrayList<MenuListDialog.MenuItem>()
		menuList.add(MenuListDialog.MenuItem(Constant.KEY_MENUITEM_DELETE, "删除"))
		//初始化弹框
		menuListDialog = MenuListDialog(this, R.layout.listview_menu_item, menuList)
		menuListDialog.inflaterViewListener = MenuItemInflaterViewListener()

		//绑定监听事件
		menuListDialog.onItemClickListener = MenuItemClickListener()
		//绑定事件之后，创建view
		menuListDialog.onCreateView()
	}

	/**菜单按钮点击的监听器*/
	inner class MenuItemClickListener: MenuListDialog.MenuItemClickListener{
		override fun onItemClick(item: MenuListDialog.MenuItem, view: View, position: Int): Boolean {
			when(item.key){
				//删除记录
				Constant.KEY_MENUITEM_DELETE->{
					val bookDownload = listData[curBookSelectPosition]
					bookDownloadManager.stopTask(bookDownload)
					bookDownloadRepository.deleteById(bookDownload.id)
					ToastUtils.toast("删除成功")
					queryData()
				}
			}
			return true
		}
	}

	/**初始化列表*/
	private fun initListView(){
		//添加适配器
		listAdapter = BookDownloadListAdapter(this, this.listData)
		listAdapter.initListView(rv_download_books)
		//取消RecyclerView刷新的闪烁动画
		(rv_download_books.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

		//列表项长按显示菜单
		listAdapter.onItemLongClickListener = object: BaseRecyclerViewAdapter.OnItemLongClickListener{
			override fun onItemLongClick(position: Int, event: MotionEvent?): Boolean {
				//记录下标
				curBookSelectPosition = position
				//打开菜单
				menuListDialog.openDialog(Gravity.NO_GRAVITY, event)
				return true
			}

		}

	}

	/**处理观察者的事件*/
	override fun handleEvent(message: Message) {
		when(message.what){
			//刷新爬取的章节名称信息
			Constant.handler_event_book_download_update_message->{
				val msg = message.data.getString("message")
				LogCatUtil.d("???", "更新消息, $msg")
				this.updateListItemMessage(message)
			}
			//刷新爬取的错误信息
			Constant.handler_event_book_download_update_error_message->{
				this.updateListItemMessage(message, true)
			}
		}
	}


	/**更新状态*/
	private fun updateListItemMessage(message: Message, error: Boolean = false){
		val bookId = message.data.getString("bookId")
		val bookCrawlerId = message.data.getLong("bookCrawlerId")

		if(TextUtils.isEmpty(bookId)){
			ToastUtils.toast("书籍id为空！请联系客服！")
			return
		}
		val bookDownload = message.obj as BookDownload
		val msg = message.data.getString("message")?:""
		//更新list数据
		val result = listData.find { it.bookId == bookId && it.bookCrawlerId == bookCrawlerId }
		if(result != null){
			val index = listData.indexOf(result)
			if(index > -1){
				result.status = bookDownload.status
				result.error = error
				result.loadingMessage = msg
				this.listAdapter.refreshDownloadItem(index, result)
			}
		}
	}

}